package com.qf.controller;

import com.qf.pojo.ResponseData;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserSys {

    @Autowired
    private UserService userService;

    @RequestMapping("/denglu")
    public ResponseData denglu(HttpSession session){
        //从session中取出user
        User user = (User) session.getAttribute("user");
        if (user==null){
            return JsonUtils.createJson(0,"无此用户");
        }
        return JsonUtils.createJson(1,user);
    }

    @RequestMapping("/register")
    public ResponseData register(@RequestBody User user){

        Boolean flag = userService.addUser(user);
        if (!flag){
            return JsonUtils.createJson(0,"注册失败");
        }
        return JsonUtils.createJson(1,flag);
    }

    @RequestMapping("/login")
    @ResponseBody
    public ResponseData login(String tel, String password,HttpSession session){

//        System.out.println("进来了");
//        System.out.println(tel+password);
        User user = userService.findUserBytel(tel,password);
        //将user存储到session中
        session.setAttribute("user",user);
        if (user==null){
            return JsonUtils.createJson(0,"用户名或者密码不正确");
        }
        return JsonUtils.createJson(1,user);
    }

    @RequestMapping("update")
    public ResponseData update(String tel,HttpSession session){
        //从session中取出user
        User user = (User) session.getAttribute("user");

//        System.out.println(user);
//        System.out.println(tel);
        //拿到现在用户的电话号码
        Boolean flag = userService.updateUser(user,tel);
        //再次通过修改后的tel查询,等到user实体
        String password = user.getPassword();
        User user1 = userService.findUserBytel(tel, password);
        //将旧的user移除session
        session.removeAttribute("user");
        //将新的user再次存入到session中
        session.setAttribute("user",user1);
        if (!flag){
            return JsonUtils.createJson(0,"修改失败");
        }
        return JsonUtils.createJson(1,"flag");
    }
}
